from flask import Blueprint, jsonify, request, Response
from models import Supplier
from extensions import db
from flask_login import login_required
import csv
from io import StringIO

suppliers_bp = Blueprint('suppliers', __name__)


@suppliers_bp.route('/suppliers', methods=['GET'])
@login_required
def get_suppliers():
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)

        suppliers = Supplier.query.paginate(page=page, per_page=per_page, error_out=False)
        serialized_suppliers = [supplier.to_dict() for supplier in suppliers.items]

        return jsonify({
            'suppliers': serialized_suppliers,
            'total': suppliers.total,
            'pages': suppliers.pages,
            'current_page': suppliers.page
        }), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@suppliers_bp.route('/suppliers/<int:id>', methods=['GET'])
@login_required
def get_supplier(id):
    try:
        supplier = Supplier.query.get_or_404(id)
        serialized_supplier = supplier.to_dict()
        return jsonify(serialized_supplier), 200
    except Exception as e:
        return jsonify({'error': '客户编号不存在'}), 400


@suppliers_bp.route('/suppliers', methods=['POST'])
@login_required
def create_supplier():
    try:
        data = request.get_json()
        existing_supplier = Supplier.query.get(data.get('customer_id'))
        if existing_supplier:
            return jsonify({'error': '该客户编号已存在，请勿重复添加'}), 400

        new_supplier = Supplier(
            id=data.get('customer_id'),
            name=data.get('customer_name'),
            short_name=data.get('customer_short_name'),
            address=data.get('address'),
            phone=data.get('company_phone'),
            email=data.get('email'),
            contact=data.get('contact_person'),
            contact_phone=data.get('contact_phone'),
            remark=data.get('remarks')
        )
        db.session.add(new_supplier)
        db.session.commit()
        return jsonify(new_supplier.to_dict()), 201
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@suppliers_bp.route('/suppliers/<int:id>', methods=['PUT'])
@login_required
def update_supplier(id):
    try:
        supplier = Supplier.query.get_or_404(id)
        data = request.get_json()

        new_customer_id = data.get('new_customer_id')
        if new_customer_id and int(new_customer_id) != supplier.id:
            if Supplier.query.get(new_customer_id):
                return jsonify({'error': '新客户编号已存在，请选择不同的编号。'}), 400
            supplier.id = int(new_customer_id)

        supplier.name = data.get('customer_name')
        supplier.short_name = data.get('customer_short_name')
        supplier.address = data.get('address')
        supplier.phone = data.get('company_phone')
        supplier.email = data.get('email')
        supplier.contact = data.get('contact_person')
        supplier.contact_phone = data.get('contact_phone')
        supplier.remark = data.get('remarks')

        db.session.commit()
        return jsonify(supplier.to_dict()), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@suppliers_bp.route('/suppliers/<int:id>', methods=['DELETE'])
@login_required
def delete_supplier(id):
    try:
        supplier = Supplier.query.get_or_404(id)
        db.session.delete(supplier)
        db.session.commit()
        return jsonify({'message': 'Supplier deleted'}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@suppliers_bp.route('/suppliers/export/csv', methods=['GET'])
@login_required
def export_suppliers_csv():
    try:
        suppliers = Supplier.query.all()
        output = StringIO()
        writer = csv.writer(output)
        writer.writerow(['id', 'name', 'short_name', 'address', 'phone', 'email', 'contact', 'contact_phone', 'remark'])
        for supplier in suppliers:
            writer.writerow([
                supplier.id, supplier.name, supplier.short_name, supplier.address,
                supplier.phone, supplier.email, supplier.contact,
                supplier.contact_phone, supplier.remark
            ])
        output.seek(0)
        return Response(
            output,
            mimetype='text/csv',
            headers={'Content-Disposition': 'attachment; filename=suppliers.csv'}
        ), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@suppliers_bp.route('/suppliers/count', methods=['GET'])
@login_required
def get_supplier_count():
    try:
        count = Supplier.query.count()
        return jsonify({'count': count}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400
